package c.x.jy.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
 
@SuppressWarnings("all")
 
public class HttpClientUtil {  
 
    
    
    protected static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String sendHttpsPost(String url, Map<String,String> map) {
		// String url ="http://localhost:8082/apollo-sms/config/getconfig";
		logger.info("请求地扯："+url);
		logger.info("请求值："+map);
		//System.out.println("请求值："+map);
		String charset="UTF-8";
		CloseableHttpClient httpclient = null;
		if(url.contains("https:")){
			
			try {
				httpclient = new SSLClient();
			} catch (Exception e) {
				e.printStackTrace();
			     return null;
				
			} 
		}else{
		 httpclient = HttpClients.createDefault();
		}
	
		// 响应对象
		CloseableHttpResponse response = null;
		try {
			 
			HttpPost httpPost = new HttpPost(url);
		
			if(map!=null){
		    //设置参数  
            List<NameValuePair> list = new ArrayList<NameValuePair>();  
            Iterator iterator = map.entrySet().iterator();  
        
    
        /*  //淘量取任务消息头需包含Authorization
    	 	if(map!=null&&map.containsKey(TaoLiangKey.TAOLIANG_TOKEN)){
        		httpPost.addHeader("Authorization", "Bearer"+map.get(TaoLiangKey.TAOLIANG_TOKEN));
        		httpPost.addHeader("Content-Type", "application/json"); 
        	}*/
        
            while(iterator.hasNext()){  
                Entry<String,Object> elem = (Entry<String, Object>) iterator.next();
                if(elem.getValue()!=null){
                list.add(new BasicNameValuePair(elem.getKey(), elem.getValue().toString()));  
                }
            }  
            if(list.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);  
                httpPost.setEntity(entity);  
          
            }  
			}
			httpPost.setConfig(getTimout());
			response = httpclient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(),charset);
	
			logger.info("发送信息成功！:{}",result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		logger.info("发送信息失败！");
		return null;

	}
	
	
	public static String sendHttpsPost(String url, JSONObject map) {
		// String url ="http://localhost:8082/apollo-sms/config/getconfig";
		logger.info("请求地扯：{}",url);
		logger.info("请求值：{}",map);
		//System.out.println("请求值："+map);
		String charset="UTF-8";
		CloseableHttpClient httpclient = null;
		if(url.contains("https:")){
			
			try {
				httpclient = new SSLClient();
			} catch (Exception e) {
				e.printStackTrace();
			     return null;
				
			} 
		}else{
		 httpclient = HttpClients.createDefault();
		}
		// 响应对象
		CloseableHttpResponse response = null;
		try {
			HttpPost httpPost = new HttpPost(url);
		 /*	if(map!=null&&map.containsKey(TaoLiangKey.TAOLIANG_TOKEN)){
		 		httpPost.addHeader("Authorization", "Bearer"+map.getString(TaoLiangKey.TAOLIANG_TOKEN));
		 		httpPost.addHeader("Content-Type", "application/json"); 
		 	}*/
		
			if(map!=null){
				 StringEntity entity = new StringEntity(map.toString(),"utf-8");//解决中文乱码问题    
		         entity.setContentEncoding("UTF-8");    
		         entity.setContentType("application/json");  
	         	httpPost.setEntity(entity);  
           
			}
			httpPost.setConfig(getTimout());
			response = httpclient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(),charset);
			//System.out.println(result);
			logger.info("发送信息成功！:{}",result);
	
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		logger.info("发送信息失败！");
		return null;

	}
	
	
	
	public static String sendHttpsPost(String url, JSONArray list,JSONObject map)  {
		// String url ="http://localhost:8082/apollo-sms/config/getconfig";
		logger.info("请求地扯："+url);
		//logger.info("请求值：{},{}",map,list);
		//System.out.println("请求值："+map);
		//System.out.println("请求值1："+list);
		String charset="UTF-8";
		CloseableHttpClient httpclient=null;
		if(url.contains("https:")){
			try {
				httpclient = new SSLClient();
			} catch (Exception e) {
				
				e.printStackTrace();
				return null;
			} 
		}else{
		 httpclient = HttpClients.createDefault();
		}
		// 响应对象
		CloseableHttpResponse response = null;
		

		try {
			HttpPost httpPost = new HttpPost(url);
		/* 	if(map!=null&&map.containsKey(TaoLiangKey.TAOLIANG_TOKEN)){
		 		httpPost.addHeader("Authorization", "Bearer"+map.getString(TaoLiangKey.TAOLIANG_TOKEN));
		 		httpPost.addHeader("Content-Type", "application/json"); 
		 	}
		*/
			if(map!=null){
				 StringEntity entity = new StringEntity(list.toString(),"utf-8");//解决中文乱码问题    
		         entity.setContentEncoding("UTF-8");    
		         entity.setContentType("application/json");  
	         	httpPost.setEntity(entity);  
           
			}
			httpPost.setConfig(getTimout());
			response = httpclient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(),charset);
			//System.out.println(result);
			logger.info("发送信息成功！:{}",result);
	
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		logger.info("发送信息失败！");
		return null;

	}
	
	
	
	public static String sendHttpsGet(String url)  {
		// String url ="http://localhost:8082/apollo-sms/config/getconfig";
		logger.info("请求地扯："+url);
		String charset="UTF-8";
		CloseableHttpClient httpclient =null;
		if(url.contains("https://")){
			httpclient =SSLClient.createSSLClientDefault();
			try {
				//httpclient = new SSLClient();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			} 
		}else{
		 httpclient = HttpClients.createDefault();
		}
		// 响应对象
		CloseableHttpResponse response = null;
		try {
			HttpGet httpPost = new HttpGet(url);
			httpPost.setConfig(getTimout());
			response = httpclient.execute(httpPost);
			String result = EntityUtils.toString(response.getEntity(),charset);
		//	System.out.println(result);
			logger.info("发送信息成功！"+result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		logger.info("发送信息失败！");
		return null;

	}
	
	
	public static RequestConfig getTimout(){
		//HttpHost proxy=new HttpHost("127.0.0.1", 8888);;//.setProxy(proxy)
		RequestConfig requestConfig = RequestConfig.custom()  
		        .setConnectTimeout(5000).setConnectionRequestTimeout(3000)  
		        .setSocketTimeout(5000).build(); 
		return requestConfig;
	}
	
	
	public static void main(String[] args) {
    	JSONObject map=new JSONObject();
		//Map map=new HashMap();
    	map.put("f", "869300034766125");
    	map.put("c", 9);
    /*	map.put("t", GetConfig.getCompanyCode());*/
    	map.put("m", "0");
    	map.put("mi", -1);
 
      String ms = null;
      
      JSONObject map1=new JSONObject();
      map1.put("message", map.toString());
      
      map1.put("neednum", 1);
      
	try {
		ms=	URLEncoder.encode(map.toString(), "utf-8");
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	//"http://testapi.goluodi.com/chengpuseng/gettask"
	//String url="https://user.test.com/app/index.php?i=2&c=entry&m=llt_advs&do=yundai&op=create";
	String url=	"https://iyfb.yunfenba.com/api/getorder?channel=jianghu&p=602518&userid=olV6-52KZxWUm-KDp0g7py287lw81";
	//String url="http://api.miniapp.goluodi.com/api/getorder?channel=chengpuseng";
	
	//System.out.println(HttpClientUtil.sendHttpsPost("https://jh1.96331.com/iot-wechat-web/querycheckoutByoid?oid=106", map1));
	//System.out.println(HttpClientUtil.sendHttpsPost("https://jh1.96331.com/iot-wechat-web/queryUserinfoById?p=40225", map1));
	//HttpClientUtil.sendHttpsPost(url, map1);
	
	System.out.println(HttpClientUtil.sendHttpsGet(url));
	
	
	
    	
	}


	
}